package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.entity.BaseMembershipGradeEntity;
import com.yuanfeng.base.entity.BaseTagClassEntity;
import com.yuanfeng.base.feign.UsermsClient;
import com.yuanfeng.base.mapper.BaseMembershipGradeMapper;
import com.yuanfeng.base.mapper.BaseTagClassMapper;
import com.yuanfeng.base.service.BaseMembershipGradeService;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.UpMemberClassDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class BaseMembershipGradeServiceImpl extends ServiceImpl<BaseMembershipGradeMapper, BaseMembershipGradeEntity>
    implements BaseMembershipGradeService{

    @Autowired
    private BaseTagClassMapper baseTagClassMapper;

    @Autowired
    private UsermsClient usermsClient;
    @Override
    public ResponseResult getMemberNameByClassId(String id) {
        BaseMembershipGradeEntity entity=this.baseMapper.selectById(id);
        return ResponseResult.success(entity);
    }

    @Override
    public Map<String, Object> queryMemberShipGradeByUserId(String userId) {
        Integer tagId= baseTagClassMapper.getMemberClassIdByUserId(userId);
        Map<String,Object> memberName= this.baseMapper.getMemberNameByClassId(tagId);
        return memberName;
    }

    @Override
    public Integer getMaxMemberIntegral() {
        return this.baseMapper.getMaxMemberIntegral();
    }

    @Override
    public ResponseResult getMemberIntegralDistance(String userId) {
        Integer presentInteger= baseTagClassMapper.queryMemberMessageListIntegral(userId);
        Map<String, Object> stringStringMap = this.baseMapper.distanceClassIntegral(presentInteger);
        return ResponseResult.success(stringStringMap);
    }

    @Override
    public ResponseResult selectdiscount() {
        BigDecimal gradeDiscount=this.baseMapper.selectOne(new LambdaQueryWrapper<BaseMembershipGradeEntity>()
                                         .eq(BaseMembershipGradeEntity::getGradeStart, CommonType.commonStatus.YES.getCode())
                                         .orderByAsc(BaseMembershipGradeEntity::getGradeDiscount)
                                         .last("LIMIT 1")).getGradeDiscount();
        return ResponseResult.success(gradeDiscount);
    }

    @Override
    public ResponseResult MembershipGradedelete(String id) {
        if(StringUtils.isNotEmpty(id)){
            this.baseMapper.update(null,new LambdaUpdateWrapper<BaseMembershipGradeEntity>()
                            .set(BaseMembershipGradeEntity::getGradeStart,CommonType.commonStatus.NO.getCode())
                            .eq(BaseMembershipGradeEntity::getId,id));
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult MembershipGradeAddOrUpdate(Map<String, String> map) {
        try {
            if(ObjectUtils.isEmpty(map.get("gradeDiscount"))){
                return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
            }
            //判断折扣大于0 或者小于等于1
            if(((new BigDecimal(map.get("gradeDiscount")).compareTo(new BigDecimal("1")) == -1) || (new BigDecimal(map.get("gradeDiscount")).compareTo(new BigDecimal("1")) == 0))
                    && (new BigDecimal(map.get("gradeDiscount")).compareTo(new BigDecimal("0")) == 1)
            ){
                if(null == map.get("id")){
                    this.baseMapper.MembershipGradeAdd(map);
                }else{
                    this.baseMapper.MembershipGradeUpdate(map);
                }
            }else{
                return  ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult upMemberClassDto(UpMemberClassDTO dto) {
        Integer gradeRule = 0;
        //判断入参是否为空
        if (dto == null) {
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }

        //根据会员等级id查询最低积分
        List<BaseMembershipGradeEntity> membershipGrades = this.baseMapper.selectList(new LambdaUpdateWrapper<BaseMembershipGradeEntity>()
                .set(BaseMembershipGradeEntity::getGradeStart,CommonType.commonStatus.YES.getCode())
                .eq(BaseMembershipGradeEntity::getId,dto.getMemberClassId())
                .orderByAsc(BaseMembershipGradeEntity::getGradeRule));
        if (membershipGrades.size()!=0) {
            BaseMembershipGradeEntity membershipGrade1 = membershipGrades.get(0);
            gradeRule = membershipGrade1.getGradeRule();
        }else{
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
        //遍历入参的id数组
        String[] memberArray = dto.getMemberArray();
        for (String memberId : memberArray) {
            Map<String,Object> map=new HashMap<>();
            map.put("userId",memberId);
            map.put("userIntegral",gradeRule);
            if(usermsClient.updateUser(map).getCode()==BizCodeEnume.OPERATION_FAILED.getCode()){
                return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
            }
            baseTagClassMapper.update(null,new LambdaUpdateWrapper<BaseTagClassEntity>()
                              .set(BaseTagClassEntity::getMemberClassId,dto.getMemberClassId())
                              .eq(BaseTagClassEntity::getMemberId,memberId));


        }

        return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryMembershipGrade(Map<String, Object> map) {
        List<BaseMembershipGradeEntity> list=this.baseMapper.selectList(new LambdaQueryWrapper<BaseMembershipGradeEntity>()
                                             .eq(BaseMembershipGradeEntity::getGradeStart,CommonType.commonStatus.YES.getCode())
                                             .orderByAsc(BaseMembershipGradeEntity::getGradeRule));
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult queryMembershipGradeByGradeRule(Map<String, Object> map) {
        QueryWrapper<BaseMembershipGradeEntity> queryWrapper = new QueryWrapper<>();

        if (null != map && null != map.get("gradeStart")) {
            queryWrapper.le("grade_start", map.get("gradeStart").toString());

        }

        if (null != map && null != map.get("userIntegral")) {
            queryWrapper.le("grade_rule", map.get("userIntegral").toString());
            queryWrapper.orderByDesc("grade_rule");
            queryWrapper.last("limit 1");
        }

        //获取积分信息
        BaseMembershipGradeEntity membershipGradeEntity = this.baseMapper.selectOne(queryWrapper);


        //根据用户id更新会员等级
        baseTagClassMapper.update(null,new LambdaUpdateWrapper<BaseTagClassEntity>()
                .eq(BaseTagClassEntity::getMemberId,map.get("userId").toString())
                .set(BaseTagClassEntity::getMemberClassId,membershipGradeEntity.getId()));

        return ResponseResult.success();
    }
}




